/*******************************************************************************
 (c) 2005-2014 Copyright, Real-Time Innovations, Inc.  All rights reserved.
 RTI grants Licensee a license to use, modify, compile, and create derivative
 works of the Software.  Licensee has the right to distribute object form only
 for use with RTI products.  The Software is provided "as is", with no warranty
 of any type, including any warranty for fitness for any purpose. RTI is under
 no obligation to maintain or support the Software.  RTI shall not be liable for
 any incidental or consequential damages arising out of the use or inability to
 use the software.
 ******************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
/* waitset_statuscond_subscriber.cs

   A subscription example

   This file is derived from code automatically generated by the rtiddsgen 
   command:

   rtiddsgen -language C# -example <arch> waitset_statuscond.idl

   Example subscription of type waitset_statuscond automatically generated by 
   'rtiddsgen'. To test them, follow these steps:

   (1) Compile this file and the example publication.

   (2) Start the subscription with the command
       objs\<arch>\waitset_statuscond_subscriber <domain_id> <sample_count>

   (3) Start the publication with the command
       objs\<arch>\waitset_statuscond_publisher <domain_id> <sample_count>

   (4) [Optional] Specify the list of discovery initial peers and 
       multicast receive addresses via an environment variable or a file 
       (in the current working directory) called NDDS_DISCOVERY_PEERS. 

   You can run any number of publishers and subscribers programs, and can 
   add and remove them dynamically from the domain.
                                   
   Example:
        
       To run the example application on domain <domain_id>:
                          
       bin\<Debug|Release>\waitset_statuscond_publisher <domain_id> 
                                                               <sample_count>  
       bin\<Debug|Release>\waitset_statuscond_subscriber <domain_id> 
                                                               <sample_count>
              
       
modification history
------------ -------
*/

public class waitset_statuscondSubscriber {

    public static void Main( string[] args ) {

        // --- Get domain ID --- //
        int domain_id = 0;
        if (args.Length >= 1) {
            domain_id = Int32.Parse(args[0]);
        }

        // --- Get max loop count; 0 means infinite loop  --- //
        int sample_count = 0;
        if (args.Length >= 2) {
            sample_count = Int32.Parse(args[1]);
        }

        /* Uncomment this to turn on additional logging
        NDDS.ConfigLogger.get_instance().set_verbosity_by_category(
            NDDS.LogCategory.NDDS_CONFIG_LOG_CATEGORY_API, 
            NDDS.LogVerbosity.NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
        */

        // --- Run --- //
        try {
            waitset_statuscondSubscriber.subscribe(
                domain_id, sample_count);
        } catch (DDS.Exception) {
            Console.WriteLine("error in subscriber");
        }
    }

    static void subscribe( int domain_id, int sample_count ) {

        // --- Create participant --- //

        /* To customize the participant QoS, use 
           the configuration file USER_QOS_PROFILES.xml */
        DDS.DomainParticipant participant =
            DDS.DomainParticipantFactory.get_instance().create_participant(
                domain_id,
                DDS.DomainParticipantFactory.PARTICIPANT_QOS_DEFAULT,
                null /* listener */,
                DDS.StatusMask.STATUS_MASK_NONE);
        if (participant == null) {
            shutdown(participant);
            throw new ApplicationException("create_participant error");
        }

        // --- Create subscriber --- //

        /* To customize the subscriber QoS, use 
           the configuration file USER_QOS_PROFILES.xml */
        DDS.Subscriber subscriber = participant.create_subscriber(
            DDS.DomainParticipant.SUBSCRIBER_QOS_DEFAULT,
            null /* listener */,
            DDS.StatusMask.STATUS_MASK_NONE);
        if (subscriber == null) {
            shutdown(participant);
            throw new ApplicationException("create_subscriber error");
        }

        // --- Create topic --- //

        /* Register the type before creating the topic */
        System.String type_name =
            waitset_statuscondTypeSupport.get_type_name();
        try {
            waitset_statuscondTypeSupport.register_type(
                participant, type_name);
        } catch (DDS.Exception e) {
            Console.WriteLine("register_type error {0}", e);
            shutdown(participant);
            throw e;
        }

        /* To customize the topic QoS, use 
           the configuration file USER_QOS_PROFILES.xml */
        DDS.Topic topic = participant.create_topic(
            "Example waitset_statuscond",
            type_name,
            DDS.DomainParticipant.TOPIC_QOS_DEFAULT,
            null /* listener */,
            DDS.StatusMask.STATUS_MASK_NONE);
        if (topic == null) {
            shutdown(participant);
            throw new ApplicationException("create_topic error");
        }

        // --- Create reader --- //



        /* To customize the data reader QoS, use 
           the configuration file USER_QOS_PROFILES.xml */
        DDS.DataReader reader = subscriber.create_datareader(
            topic,
            DDS.Subscriber.DATAREADER_QOS_DEFAULT,
            null,
            DDS.StatusMask.STATUS_MASK_ALL);
        if (reader == null) {
            shutdown(participant);
            throw new ApplicationException("create_datareader error");
        }

        // Get narrowed datareader
        waitset_statuscondDataReader waitset_reader =
            (waitset_statuscondDataReader)reader;

        /* Get status conditions
         * ---------------------
         * Each entity may have an attached Status Condition. To modify the
         * statuses we need to get the reader's Status Conditions first.
         */
        DDS.StatusCondition status_condition = reader.get_statuscondition();

        /* Set enabled statuses
         * --------------------
         * Now that we have the Status Condition, we are going to enable the
         * status we are interested in: knowing that data is available
         */
        try {
            status_condition.set_enabled_statuses(
                (DDS.StatusMask)DDS.StatusKind.DATA_AVAILABLE_STATUS);
        } catch (DDS.Exception e) {
            shutdown(participant);
            throw new ApplicationException("set_enabled_statuses error {0}",
                e);
        }

        /* Create and attach conditions to the WaitSet
         * -------------------------------------------
         * Finally, we create the WaitSet and attach both the Read Conditions
         * and the Status Condition to it.
         */
        DDS.WaitSet waitset = new DDS.WaitSet();


        /* Attach Status Conditions */
        try {
            waitset.attach_condition(status_condition);
        } catch (DDS.Exception e) {
            shutdown(participant);
            throw new ApplicationException("set_enabled_statuses error {0}",
                e);

        }
        // --- Wait for data --- //
        DDS.Duration_t timeout;
        timeout.nanosec = (uint)500000000;
        timeout.sec = 1;

        /* Main loop */
        for (int count = 0; (sample_count == 0) || (count < sample_count);
                 ++count) {
            DDS.ConditionSeq active_conditions = new DDS.ConditionSeq();

            // The triggered condition(s) will be placed in active_conditions
            try {
                waitset.wait(active_conditions, timeout);
                Console.WriteLine("got {0} active conditions", active_conditions.length);
            } catch (DDS.Retcode_Timeout) {
                Console.WriteLine("Wait timed out!! No conditions were " +
                    "triggered.");
                continue;
            } catch (DDS.Exception e) {
                Console.WriteLine("wait error {0}", e);
                break;
            }
            for (int i = 0; i < active_conditions.length; ++i) {
                /* In this case, we have only a single condition, but
                   if we had multiple, we would need to iterate over
                   them and check which one is true.  Leaving the logic
                   for the more complex case. */
                if (active_conditions.get_at(i) == status_condition) {
                    DDS.StatusMask triggeredmask =
                        waitset_reader.get_status_changes();

                    if ((triggeredmask &
                        (DDS.StatusMask)
                        DDS.StatusKind.DATA_AVAILABLE_STATUS) != 0) {
                        /* Current conditions match our conditions to read data, so
                         * we can read data just like we would do in any other
                         * example. */
                        waitset_statuscondSeq data_seq
                                = new waitset_statuscondSeq();
                        DDS.SampleInfoSeq info_seq
                            = new DDS.SampleInfoSeq();

                        /* Access data using read(), take(), etc.  If 
                         * you fail to do this the condition will 
                         * remain true, and the WaitSet will wake up 
                         * immediately - causing high CPU usage when it
                         * does not sleep in the loop 
                         */
                        bool follow = true;
                        while (follow) {
                            try {
                                waitset_reader.take(
                                    data_seq,
                                    info_seq,
                                    DDS.ResourceLimitsQosPolicy.LENGTH_UNLIMITED,
                                    DDS.SampleStateKind.ANY_SAMPLE_STATE,
                                    DDS.ViewStateKind.ANY_VIEW_STATE,
                                    DDS.InstanceStateKind.ANY_INSTANCE_STATE);

                                System.Int32 data_length = data_seq.length;
                                for (int j = 0; j < data_length; ++j) {
                                    if (!info_seq.get_at(j).valid_data) {
                                        Console.WriteLine("Got metadata");
                                        continue;
                                    }
                                    waitset_statuscondTypeSupport.print_data(data_seq.get_at(j));
                                }
                            } catch (DDS.Retcode_NoData) {
                                /* When there isn't data, the subscriber stop to
                                 * take samples
                                 */
                                follow = false;
                            } finally {
                                /* Return the loaned data */
                                waitset_reader.return_loan(data_seq, info_seq);
                            }
                        }
                    }
                }
            }
        }
        // --- Shutdown --- //

        /* Delete all entities */
        shutdown(participant);
    }


    static void shutdown(
        DDS.DomainParticipant participant ) {

        /* Delete all entities */

        if (participant != null) {
            participant.delete_contained_entities();
            DDS.DomainParticipantFactory.get_instance().delete_participant(
                ref participant);
        }

        /* RTI Connext provides finalize_instance() method on
           domain participant factory for users who want to release memory
           used by the participant factory. Uncomment the following block of
           code for clean destruction of the singleton. */
        /*
        try {
            DDS.DomainParticipantFactory.finalize_instance();
        }
        catch(DDS.Exception e) {
            Console.WriteLine("finalize_instance error {0}", e);
            throw e;
        }
        */
    }
}


